package cn.hy.dataSync.transport.record;


import cn.hy.dataSync.element.Column;
import cn.hy.dataSync.element.Record;
import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * record 默认实现
 */
public class DefaultRecord implements Record {

    private static final int RECORD_AVERAGE_COLUMN_NUMBER = 64;

    private final Map<String, Column> columns; // 一行记录，结构用map 组装。

    private final Map<String, Object> transforms;

    public DefaultRecord() {
        this.columns = new HashMap<>(RECORD_AVERAGE_COLUMN_NUMBER);
        this.transforms = new HashMap<>(RECORD_AVERAGE_COLUMN_NUMBER / 4);
    }

    @Override
    public void addColumn(String name, Column column) {
        columns.put(name, column);
    }

    @Override
    public Column getColumn(String name) {
        return columns.get(name);
    }

    @Override
    public void setColumn(String name, final Column column) {
        columns.put(name, column);
    }

    @Override
    public int getColumnNumber() {
        return this.columns.size();
    }

    @Override
    public String toString() {
        return JSON.toJSONString(columns);
    }

    @Override
    public Object get(Object key) {
        Object value = transforms.get(key);
        if (Objects.isNull(value)) {
            Column column = getColumn((String) key);
            if (Objects.nonNull(column)) {
                value = column.getRawData();
            }
        }
        return value;
    }

    @Override
    public Object put(String name, Object object) {
        return this.transforms.put(name, object);
    }
}
